package com.zjh.admin.service.impl;

import cn.hutool.core.lang.Assert;
import com.zjh.admin.entity.DAO.SysUserEntity;
import com.zjh.admin.entity.VO.ResetPasswordVO;
import com.zjh.admin.entity.VO.SysUserVO;
import com.zjh.admin.mapper.sysUserMapper;
import com.zjh.admin.service.UserService;
import com.zjh.common.config.SecurityConfig;
import com.zjh.common.config.SnowflakeConfig;
import com.zjh.common.entity.LoginUser;
import com.zjh.common.exception.ServiceException;
import com.zjh.common.utils.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private sysUserMapper mapper;

    @Resource
    private SnowflakeConfig snowflakeConfig;

    @Resource
    private SecurityConfig securityConfig;

    @Override
    public List<SysUserEntity> getAllUsers() {
        List<SysUserEntity> allUsers = mapper.getAllUsers();
        allUsers.forEach(user -> {
            // 密码字段置为空
            user.setPassword("");
        });
        return allUsers;
    }

    @Override
    public SysUserEntity getUserById(Long id) {
        return mapper.getUserById(id);
    }

    @Override
    public void deleteUserById(int id) {
        mapper.deleteUserById(id);
    }

    @Override
    public void updateUser(SysUserEntity usr) {
        // 更新时间
        usr.setUpdatedAt(LocalDateTime.now());
        mapper.updateUser(usr);
    }

    @Override
    public Boolean resetPasswordValid(ResetPasswordVO resetPasswordVO) {
        if (StringUtils.isBlank(resetPasswordVO.getPreviousPassword())) {
            throw new ServiceException("初始密码不能为空");
        }
        Long userId = resetPasswordVO.getUserId();
        SysUserEntity userById = this.getUserById(userId);

        String previousPassword = resetPasswordVO.getPreviousPassword();
        boolean matches = securityConfig.bCryptPasswordEncoder().matches(previousPassword, userById.getPassword());

        return matches;
    }

    @Override
    public void resetPassword(ResetPasswordVO resetPasswordVO) {
        Assert.notNull(resetPasswordVO.getNewPassword(), "新密码不能为空");

        Long userId = resetPasswordVO.getUserId();

        LoginUser loginUser = RequestContext.getLoginUser();
        // 系统管理员
        if (!(loginUser.getRoleId() == 1 || loginUser.getUserId() == userId)) {
            throw new ServiceException("非系统管理员或本用户不可以重置秘密");
        }

        // 非管理员修改密码 需要原来密码验证
        if (loginUser.getRoleId() != 1) {
            Assert.notNull(resetPasswordVO.getPreviousPassword(), "初始密码不能为空");
            if (!this.resetPasswordValid(resetPasswordVO)) {
                throw new ServiceException("初始密码错误");
            }
        }


        SysUserEntity usr = this.getUserById(userId);
        // 重置密码
        usr.setPassword(securityConfig.bCryptPasswordEncoder().encode(resetPasswordVO.getNewPassword()));
        usr.setUpdatedAt(LocalDateTime.now());
        mapper.updateUserPassword(usr);
    }

    @Override
    public void addUser(SysUserVO usr) {
        SysUserEntity userByUsername = mapper.getUserByUsername(usr.getUsername());
        if (!Objects.isNull(userByUsername)) {
            throw new ServiceException("用户已经存在");
        }

        SysUserEntity user = new SysUserEntity();
        BeanUtils.copyProperties(usr, user);

        user.setUserId(snowflakeConfig.snowflakeId());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setIsActive(true);

        mapper.addUser(user);
    }


    @Override
    public SysUserEntity getUserByUsername(String username) {
        return mapper.getUserByUsername(username);

    }



}
